//
//  Mytools.m
//  7UGame
//
//  Created by 111 on 2017/2/14.
//  Copyright © 2017年 111. All rights reserved.
//

#import "Mytools.h"
#import <CommonCrypto/CommonDigest.h>
#import "UITableView+HD_NoList.h"
@implementation Mytools

+(BOOL) verifyURL:(NSString *)url{
    NSString *pattern = @"^(((http[s]{0,1}|ftp|Http[s]{0,1})://)?[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:url];
    return isMatch;
}


+(NSString *)getMD5code:(NSString *)pswStr{
    NSString *resultStr = nil;//加密后的结果
    const char *cStr = [pswStr UTF8String];//指针不能变，cStr指针变量本身可以变化
    unsigned char result[16];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    resultStr = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                 result[0], result[1], result[2], result[3],
                 result[4], result[5], result[6], result[7],
                 result[8], result[9], result[10], result[11],
                 result[12], result[13], result[14], result[15]
                 ];
    return resultStr;
}
+(NSInteger)getCurrentTimestamp{
    //获取系统当前的时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSInteger newA = a;
    return newA;
}
+ (NSString *)timeStampTotime:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate* date =[NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
+(NSDate *)getCurrentDate{
    //以下为准确时间
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}
+(NSString*)encodeString:(NSString*)unencodedString{
    NSString *urlStr = [unencodedString stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet   characterSetWithCharactersInString:@"?!@#$^&%*+,:;='\"`<>()[]{}/\\|   "] invertedSet]];
    return urlStr;
}

//字符串转日期
+(NSDate*)dateStrToDate:(NSString *)dateStr{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date =[dateFormat dateFromString:dateStr];
//    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    return date;
}
+(NSDate*)dateStrToDate:(NSString *)dateStr withFormat:(NSString*)format{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:format];
    NSDate *date =[dateFormat dateFromString:dateStr];
//    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    return date;
}
+(NSString *)dateToDateStr:(NSDate*)date{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate *date2 = [date dateByAddingTimeInterval:-8 * 60 * 60];
    NSString *currentDateStr = [dateFormat stringFromDate:date];
    return currentDateStr;
}
+(NSString *)numberToMoneyFormatter:(long)num{
    NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString * newNumber = [formatter stringFromNumber:[NSNumber numberWithLong:num]];
    return newNumber;
}

+(NSString*)deleteSpaceInput:(NSString *)str{
    if ([str containsString:@" "]) {
        str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    return str;
}
#pragma mark json格式字符串转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark 字典转json格式字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",parseError);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
    
}

#pragma mark 数组转json格式字符串
+ (NSString*)ArrtionaryToJson:(NSMutableArray *)arr
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",parseError);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
    
}

/**验证是不是邮箱*/
+(BOOL)isEmail:(NSString *)email
{
    /**
     *  前半部分（由字母、数字和（.)、_ 、%、+、- 等符号组成）中间部分（由数字、字母组成和(.)、-等符号组成）最后部分(由 . 和数字组成，最少2个字符，最多四个字符)
     */
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    if ([emailTest evaluateWithObject:email]) {
        return YES;
    }else{
        return NO;
    }
}
+(BOOL)isEnglish:(NSString*)text{
    NSString *emailRegex = @"[A-Za-z]$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    if ([emailTest evaluateWithObject:text]) {
        return YES;
    }else{
        return NO;
    }
}
/**验证是不是身份证号码*/
+(BOOL)isIdCardNum:(NSString *)IdCardNumber
{
    if (IdCardNumber.length != 18) {
        return NO;
    }
    //15位身份证为第一代身份证，在2013年就停止使用
    //身份证格式 18位数字组成 或者17位数字+xX
    NSString *idCardRegex = @"\\d{18}$|(\\d{17}[xX])$";
    NSPredicate *idCardTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", idCardRegex];
    if ([idCardTest evaluateWithObject:IdCardNumber]) {
        return YES;
    }else{
        return NO;
    }
}

//日期大小比较
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //stringFromDate这个方法加了八小时
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    //dateFromString这个方法减了八小时，这狗日的
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
//    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result ==NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

+(BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

//银行卡
+(BOOL)validateBankCardNumber:(NSString *)bankCardNumber
{
    BOOL flag;
    if (bankCardNumber.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{15,30})";
    NSPredicate *bankCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [bankCardPredicate evaluateWithObject:bankCardNumber];
}

//从字符串中获取数字
+(NSString *)getNumberForString:(NSString *)str{
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z.-./.(.)]" options:0 error:NULL];
    NSString *string = str;
    NSString *result = [regular stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
    return result;
    
}

//去掉utc时间
+ (NSString *)htcTimeToLocationStr:(NSString*)utcDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    
    NSDate *dateFormatted = [dateFormatter dateFromString:utcDate];
    //输出格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted];
    return dateString;
}
+(NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3)){
        return 28;
    }
    if(year % 400 == 0)
        return 29;
    if(year % 100 == 0)
        return 28;
    return 29;
}

+(UIColor*)mostColor:(UIImage*)image{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(image.size.width, image.size.height);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:0.75];//([MaxColor[3] intValue]/255.0f)
}

+(NSString*)returnDecimalNumStr:(NSString*)numStr{
    NSString *doubleString  = [NSString stringWithFormat:@"%lf", [numStr doubleValue]];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}

+(BOOL)IsChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){
            return YES;
        }        
    }
    return NO;
}
+(UIImage*)viewBecomeImage:(UIView*)v{
    CGRect rect = v.frame;
    if ([v isKindOfClass:[UIScrollView class]]) {
        rect.size = ((UIScrollView *)v).contentSize;
    }
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    [v.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+(UIImage *)scrollViewBecomeImage:(UIScrollView *)scrollView{
    UIImage* image = nil;
    UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, NO, [UIScreen mainScreen].scale);
    {
        CGPoint savedContentOffset = scrollView.contentOffset;
        CGRect savedFrame = scrollView.frame;
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
         
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
         
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
     
    if (image != nil) {
        return image;
    }
    return nil;
}
+(NSString *)getMoneyFormat:(NSString*)money{
    if ([money containsString:@"￥"]) {
        money = [money stringByReplacingOccurrencesOfString:@"￥" withString:@""];
    }
    NSRange range = [money rangeOfString:@"."];    
    if (range.location == NSNotFound) {//没找到小数点就是整型或者非法字符
        BOOL isInt = [self isPureInt:money];
        if (money.length==0) {
            return @"";
        }
        if (!isInt) {
            XHQHUDErrorText(@"数字格式错误，请重输");
            return @"";
        }
    }else{
        BOOL isFloat = [self isPureFloat:money];
        if (!isFloat) {
            XHQHUDErrorText(@"数字格式错误，请重输");
            return @"";
        }else{//如果是浮点数，就判断是否是两位小数
            NSInteger floatLength = money.length - range.location - 1;
            if (floatLength>2) {
                return [money substringWithRange:NSMakeRange(0, range.location+3)];
            }
        }
    }
    return money;
}
//大于等于8.0   ps：currentUserNotificationSettings在iOS10 废弃
+ (BOOL)isUserNotificationEnable { // 判断用户是否允许接收通知
    BOOL isEnable = NO;
    UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
    isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    return isEnable;
}


+(BOOL)hasIllegalCharacter:(NSString *)content {
    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}

+(UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}
+(NSString *)formatFloat:(float)f
{
    if (fmodf(f, 1)==0) {//如果有一位小数点
        return [NSString stringWithFormat:@"%.0f",f];
    } else if (fmodf(f*10, 1)==0) {//如果有两位小数点
        return [NSString stringWithFormat:@"%.1f",f];
    } else {
        return [NSString stringWithFormat:@"%.2f",f];
    }
}
+(void)deleteAllUserDefaules{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [userDefaults dictionaryRepresentation];
    NSArray * keyArr = @[@"token",@"token_type",@"refresh_token",@"userID",@"password"];
    for(NSString *key in dic){
        for (NSString * name in keyArr) {
            if ([key isEqualToString:name]) {
                [userDefaults removeObjectForKey:key];
            }
        }
    }
    [userDefaults synchronize];
}
+ (NSData *)dictionary2JsonData:(NSDictionary *)dict
{
    // 转成Json数据
    if ([NSJSONSerialization isValidJSONObject:dict])
    {
        NSError *error = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
        if(error)
        {
            NSLog(@"[%@] Post Json Error", [self class]);
        }
        return data;
    }
    else
    {
        NSLog(@"[%@] Post Json is not valid", [self class]);
    }
    return nil;
}

+ (NSDictionary *)jsonData2Dictionary:(NSData *)jsonData
{
    if (jsonData == nil) {
        return nil;
    }
    NSError *err = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if (err || ![dic isKindOfClass:[NSDictionary class]]) {
        NSLog(@"Json parse failed");
        return nil;
    }
    return dic;
}
+(NSString * )judgeIdNumInput:(NSString*)text{
    if(text.length >0){
        if (text.length<18) {
            if (![Mytools isPureInt:text]) {
                XHQHUDErrorText(@"身份证格式不正确");
                text = [text substringWithRange:NSMakeRange(0, text.length -1)];
                return text;
            }
        }else{
            if (text.length == 18) {
                if (![Mytools isIdCardNum:text]) {
                    XHQHUDErrorText(@"身份证格式不正确");
                    text = [text substringWithRange:NSMakeRange(0, text.length -1)];
                    return text;
                }
            }else{
                NSString * str = [text substringWithRange:NSMakeRange(0, 18)];
                text = str;
            }
        }
        return text;
    }
    return @"";
}
#pragma mark -- 拼接参数
+(NSString *)dealWithParam:(NSDictionary *)param{
    NSArray *allkeys = [param allKeys];
    NSMutableString *result = [NSMutableString string];
    
    for (NSString *key in allkeys) {
        NSString *string = [NSString stringWithFormat:@"%@=%@&", key, param[key]];
        [result appendString:string];
    }
    if (result.length>0) {
        NSString * final = [result substringWithRange:NSMakeRange(0, result.length-1)];
        return final;
    }else{
        return @"";
    }
}
+(BOOL)isTel:(NSString*)tel{
    NSString *telRegex = @"^0\\d{2,3}-\\d{7,8}$";
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    return [telTest evaluateWithObject:tel];
}
+(NSArray *)filterUrlWithString:(NSString*)str{
    NSString * prex = @"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
    NSError*error;
    NSRegularExpression*regex = [NSRegularExpression regularExpressionWithPattern:prex options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray*arrayOfAllMatches = [regex matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length)];
    NSMutableArray * arr = [NSMutableArray new];
    for(NSTextCheckingResult*match in arrayOfAllMatches){
        NSString* substringForMatch = [str substringWithRange:match.range];
        [arr addObject:substringForMatch];
    }
    return arr.copy;
}
+(void)NeedResetNoViewWithTable:(UITableView*)tab andArr:(NSMutableArray*)arr{
    if (arr.count>0) {
        [tab dismissNoView];
    }else{
        [tab dismissNoView];
        [tab showNoView:@"暂无数据" image:Image(@"empty_icon") certer:CGPointZero];
    }
}
@end
